package com.iss.efi.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

public class SymmetricEncryptionUtil {
    private static final String ALGORITHM = "AES";
    private static  byte[] keyValue = "2a92fdbb25ef4b17ba3030fa6f512765".getBytes(); // 示例密钥，实际应用中应从安全存储中获取


    public static void setKeyValue(String key){
        keyValue = key.getBytes();
    }
    public static String encrypt(String valueToEnc) throws Exception {
        Key secretKey = new SecretKeySpec(keyValue, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedValue = cipher.doFinal(valueToEnc.getBytes());
        return Base64.getEncoder().encodeToString(encryptedValue);
    }

    public static String decrypt(String encryptedValueStr) throws Exception {
        Key secretKey = new SecretKeySpec(keyValue, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] encryptedValue = Base64.getDecoder().decode(encryptedValueStr);
        byte[] decryptedValue = cipher.doFinal(encryptedValue);
        return new String(decryptedValue);
    }

    public static void main(String[] args) throws Exception {

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("serviceName","yhlGetService");
        JSONArray jsonArray=new JSONArray();
        jsonArray.add("212");
        jsonObject.put("data",jsonArray);
        String s= JSON.toJSONString(jsonObject) ;
        System.out.println(s);
    }
}

